#!/usr/bin/env node
'use strict';
var config = require("./lib/config");
var webdep = require("./lib/webdep");
var fs = require("fs");
var path = require("path");
var program = require('commander');
var child_process = require('child_process');
program
    .version(config.packageInformation.version)
    .option('-p, --port [port]', 'Set the port number to use. Defaults to 9001')
    .option('-c, --configfile [configfile]', 'Set the path to the config file to be used. Default to ./webhook.json')
    .option('-d, --daemon', 'Run the oschina-webhook as a deamon')
    //.option('-r, --repo <repo>', 'The repo to look out for. This option must be used together with the --branch and --command options.')
    //.option('-b, --branch <branch>', 'The branch to react to. This option must be used with the --repo and --command options.')
    //.option('-co, --command <command>', 'The command to use to deploy. This option must be used with the --repo and --branch options.')
    .option('-s, --stop', 'Stop oschina-webhook that was run as a deamon')
    .option('-l, --log <log>', 'Where to log')
    .parse(process.argv);
var options = {};
options.port = program.port || config.port;
options.config = program.configfile || config.file;

var appCommand = process.platform.indexOf('win') >= 0 && process.platform != 'darwin' ? 'oschina-webhook.cmd' : "oschina-webhook";
var deploysConfigFile = path.resolve(process.cwd(), options.config);
if (!fs.existsSync(deploysConfigFile)) { // || (!options.repo && !options.branch && !options.command)) {
    console.error("No config file found at %s or no repo configured at the command line.", deploysConfigFile);
    console.log("");
    console.error("You can either set the configuration in a config file and point to it with the --configfile option.");
    //console.error(", or set the --repo, --branch and --command options.");
    console.log("");
    process.exit("No config file found");
}
else if (fs.existsSync(deploysConfigFile)) {
    options = JSON.parse(fs.readFileSync(deploysConfigFile, 'utf8'));
    options.config = program.configfile;
}
// command line args are more important
if (program.port) {
    options.port = program.port;
}

if (program.daemon) {
    setupDaemon(options);
}
else if (program.stop) {
    var pid = fs.readFileSync(path.resolve(__dirname, 'webdep.pid'), "utf-8");
    child_process.exec("kill " + pid, function (err, data) {
        if (err) {
            console.log(err, data);
        }
        else {
            console.log("Stopped webhook-deployer daemon with PID %s", pid);
        }
    });
}
else {
    webdep.init(options);
}


function setupDaemon(options) {
    var out = fs.openSync(options.log, 'a');
    var err = fs.openSync(options.log, 'a');
    var child=child_process.spawn('oschina-webhook',{
        detached: true,
        stdio: [ 'ignore', out, err ]
        //cwd: path.resolve(__dirname, "../")
    });
    fs.writeFileSync(path.resolve(__dirname, 'webdep.pid'), child.pid, "utf-8");
    child.unref();
    return;
    var spawnOptions = {
        detached: true,
        stdio: ['ignore', 'pipe', 'pipe'],
        cwd: path.resolve(__dirname, "../")
    };
    var out;
    var err;
    if (program.log) {
        var logFile = path.resolve(process.cwd(), program.log);
        out = fs.openSync(logFile, 'a');
        err = fs.openSync(logFile, 'a');
        spawnOptions.stdio = ['ignore', out, err];
    }
    var webdepArgs = [];
    webdepArgs.push("--port");
    webdepArgs.push(options.port);

    if (options.config) {
        webdepArgs.push("--configfile");
        webdepArgs.push(deploysConfigFile);
    }
    var child = child_process.spawn(appCommand, webdepArgs, spawnOptions);
    // set up objects dor stdout and stderr depending on where to put it
    var so = null;
    var se = null;

    if (program.log) {
        se = so = fs.createReadStream(logFile);
    }
    else {
        so = child.stdout;
        se = child.stderr;
    }
    fs.writeFileSync(path.resolve(__dirname, 'webdep.pid'), child.pid, "utf-8");
    so.on('data', function (data) {
        if (data.toString().indexOf("Started") > -1) {
            console.log("Staring oschina-webhook %s as a daemon with port", webdep.packageInformation.version, options.port);
            console.log(path.resolve(__dirname, 'webdep.pid'));
            process.exit();
        }
        else if (data.toString() != "\n") {
            console.log(data.toString());
        }

    });

    se.on('data', function (data) {
        if (data.toString().indexOf("EADDRINUSE") > -1) {
            console.log("oschina-webhook coudnt start because the port is already being used.");
        }
        else {
            //console.log(data.toString());
        }
    });
    child.unref();
}
module.exports = webdep;
